package ro.sep.web.services.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import ro.sep.web.dao.IProductDao;
import ro.sep.web.services.ISearchEngine;
import ro.sep.web.services.model.SearchSiteResult;
import ro.sep.web.utils.IHasSiteResults;
import ro.sep.web.utils.SearchSiteEngine;

public class SearchEngineImpl implements ISearchEngine,IHasSiteResults {

	@Autowired
	private IProductDao productDao;
	private List<SearchSiteResult> siteResults = new ArrayList<SearchSiteResult>();
	
	public void setProductDao(IProductDao productDao) {
		this.productDao = productDao;
	}

	@Override
	public List<SearchSiteResult> search(String text) {
		/*List<SearchSiteResult> mockSiteResults = new ArrayList<SearchSiteResult>();
		for (int j = 0; j < 5; j++) {
			List<SearchResult> mockResults = new ArrayList<SearchResult>();
			SearchResult searchResult = null;
			for (int i = 0; i < 4; i++) {
				searchResult = new SearchResult();
				searchResult.setUrl("url" + i);
				searchResult.setProductName("product" + i);
				searchResult.setDescription("description" + i);
				searchResult.setPrice(new BigDecimal(3.4 + i));
				mockResults.add(searchResult);
			}
			SearchSiteResult searchSiteResult = new SearchSiteResult();
			searchSiteResult.setSiteName("siteName" + j);
			searchSiteResult.setUrlToSite("urlToSite" + j);
			searchSiteResult.setListOfResults(mockResults);
			mockSiteResults.add(searchSiteResult);
		}
		return mockSiteResults;*/
		Resource res = new ClassPathResource("sites.txt");
		List<SearchSiteEngine> threads = new ArrayList<SearchSiteEngine>();
		Scanner scanner = null;
		try {
			scanner = new Scanner(res.getInputStream());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String[] line;
		while (scanner.hasNextLine()) {
			line = scanner.nextLine().split(" ");
			threads.add(new SearchSiteEngine(this, productDao, text, line[0], line[1]));
		}
		for (SearchSiteEngine thread : threads) {
			thread.start();
		}
		for (SearchSiteEngine thread : threads) {
			try {
				thread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return siteResults;
		/*List<SearchSiteResult> mockSiteResults = new ArrayList<SearchSiteResult>();
		List<SearchResult> results = productDao.getSearchResult(text, "emag");
		SearchSiteResult searchSiteResult = new SearchSiteResult();
		searchSiteResult.setSiteName("siteName0");
		searchSiteResult.setUrlToSite("urlToSite0");
		searchSiteResult.setListOfResults(results);
		mockSiteResults.add(searchSiteResult);
		return mockSiteResults;*/
	}

	@Override
	public synchronized void addSiteResult(SearchSiteResult searchSiteResult) {
		siteResults.add(searchSiteResult);
	}
	
}
